package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.*;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String name = request.getParameter("name");
        String pid = request.getParameter("pid");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");

        // 准备输入参数
        List<String> input = new ArrayList<>();
        input.add(name);
        input.add(pid);
        input.add(email);
        input.add(phone);
        input.add(password);

        // 创建 User 实例
        User user = new User();

        // 调用注册函数
        boolean isRegistered = user.Registration(input);

        if (isRegistered) {
            // 将注册请求存入ServletContext
            List<Map<String, String>> pendingRequests = (List<Map<String, String>>) getServletContext().getAttribute("pendingRequests");
            if (pendingRequests == null) {
                pendingRequests = new ArrayList<>();
            }
            
            Map<String, String> requestData = new HashMap<>();
            requestData.put("type", "registration");
            requestData.put("uid", "null");
            requestData.put("name", name);
            requestData.put("pid", pid);
            requestData.put("email", email);
            requestData.put("phone", phone);
            requestData.put("is_registered", "0");
            requestData.put("identity", "2");
            requestData.put("password", password);
            pendingRequests.add(requestData);
            
            getServletContext().setAttribute("pendingRequests", pendingRequests);
            response.sendRedirect("login.jsp?pending=true");
        } else {
            // 注册失败，返回注册页面并显示错误信息
            request.setAttribute("errorMessage", "注册失败，请检查输入信息。");
            request.getRequestDispatcher("userRegister.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通常将 GET 请求转发到 POST 处理方法
        doPost(request, response);
    }
}